package com.selvn.encryptnote;

import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class NoteEdit extends Activity
{

	private EditText mTitleText;
	private EditText mBodyText;
	private Long mRowId;
	private Button confirmButton;

	@Override
	protected void onCreate( Bundle savedInstanceState )
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_edit);

		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);

		confirmButton = (Button) findViewById(R.id.confirm);

		mRowId = savedInstanceState != null ? savedInstanceState.getLong(Config.DBID) : null;
		if (mRowId == null)
		{
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras.getLong(Config.DBID) : null;
		}
		populateFields();
	}

	@Override
	public boolean onCreateOptionsMenu( Menu menu )
	{
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_edit, menu);
		return super.onCreateOptionsMenu(menu);
	}

	// 主菜单被点击时调用这里
	@Override
	public boolean onOptionsItemSelected( MenuItem item )
	{
		switch (item.getItemId())
		{
			case R.id.Menu_edit_Save:
				Func.handle_return_code(this, SaveNote());
				break;
			case R.id.Menu_edit_Set_tip:
				break;
			case R.id.Menu_edit_return:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(R.string.return_confirm_description).setCancelable(false)
				        .setPositiveButton(R.string.positiveButtonText, new DialogInterface.OnClickListener()
				        {
					        public void onClick( DialogInterface dialog, int id )
					        {
						        setResult(RESULT_CANCELED);
						        finish();
					        }
				        }).setNegativeButton(R.string.negativeButtonText, new DialogInterface.OnClickListener()
				        {
					        public void onClick( DialogInterface dialog, int id )
					        {
						        dialog.cancel();
					        }
				        });
				builder.create().show();
				break;
			default:
				return super.onOptionsItemSelected(item);
		}
		return false;
	}

	private void populateFields()
	{
		if (mRowId != null)
		{
			HashMap<String, String> note = NoteModel.getNote(this, Long.toString(mRowId));
			mTitleText.setText(String.valueOf(note.get(Config.DBTITLE)));
			mBodyText.setText(String.valueOf(note.get(Config.DBBODY)));
			SwitchEditMode(Config.VIEW_MODE);
		} else
		{
			SwitchEditMode(Config.EDIT_MODE);
		}
	}

	private void SwitchEditMode( int mode1 )
	{
		switch (mode1)
		{
			case Config.VIEW_MODE:
				mTitleText.setFocusable(false);
				mTitleText.setFocusableInTouchMode(false);
				mBodyText.setFocusable(false);
				mBodyText.setFocusableInTouchMode(false);
				confirmButton.setText(R.string.editButtonText);
				confirmButton.setOnClickListener(new View.OnClickListener()
				{
					public void onClick( View view )
					{
						SwitchEditMode(Config.EDIT_MODE);
					}
				});
				break;
			case Config.EDIT_MODE:
				// setResult(RESULT_OK);
				// finish();
				mTitleText.setFocusable(true);
				mTitleText.setFocusableInTouchMode(true);
				mBodyText.setFocusable(true);
				mBodyText.setFocusableInTouchMode(true);
				confirmButton.setText(R.string.save_and_return);
				// Func.Toast(this, R.string.startEditToast);
				confirmButton.setOnClickListener(new View.OnClickListener()
				{
					public void onClick( View view )
					{
						int save_flag = SaveNote();
						if (save_flag == Config.SAVE_FAILED_BLANK)
						{
							Toast.makeText(getApplicationContext(), R.string.save_failed_blank, Toast.LENGTH_SHORT).show();
						}
						if (save_flag == Config.SAVE_SUCCEED)
						{
							setResult(RESULT_OK);
							finish();
						}
					}
				});
				break;
		}
	}

	private int SaveNote()
	{
		String title = mTitleText.getText().toString().trim();
		String body = mBodyText.getText().toString().trim();
		if (TextUtils.isEmpty(title) || TextUtils.isEmpty(body))
		{
			return Config.SAVE_FAILED_BLANK;
		} else if (mRowId == null)
		{
			// save as a new note
			ContentValues values = new ContentValues();
			values.put(Config.DBTITLE, title);
			values.put(Config.DBBODY, body);
			Uri uri = NoteModel.insert(this, values);
			long id = ContentUris.parseId(uri);
			if (id > 0)
			{
				mRowId = id;
			}
		} else
		{
			ContentValues values = new ContentValues();
			values.put(Config.DBTITLE, title);
			values.put(Config.DBBODY, body);
			NoteModel.update(this, values, mRowId);
		}
		return Config.SAVE_SUCCEED;
	}

	@Override
	protected void onSaveInstanceState( Bundle outState )
	{
		super.onSaveInstanceState(outState);
		outState.putLong(Config.DBID, mRowId);
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		// saveState();
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		populateFields();
	}

	@Override
	public void onConfigurationChanged( Configuration newConfig )
	{
		super.onConfigurationChanged(newConfig);
		//Toast.makeText(this, R.string., TRIM_MEMORY_BACKGROUND)
		//Func.Toast(this, "test test");
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
		{
			Log.i("", "********this is a portrait");
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
		{
			Log.i("", "this is a landscape *************");
		}
	}
}
